<template>
  <div>
    <form :action="postActionAverge" method="post" enctype="multipart/form-data" target="id_iframe">
      <input type="file" name="file">

      <input type="file" name="avatar" id="imgFile"></input>

      <button @click="submit">submit</button>
    </form>

    <div id="img1" class="image-container target">
      <img src="" class="noavatar" />
    </div>

    <div class="image-container small" id="preview-small">
      <div id="img2" class="image-wrapper">
        <img src="" class="noavatar" />
      </div>
    </div>

    <iframe id="id_iframe" name="id_iframe" style="display:none;">
    </iframe>
  </div>
</template>

<script>
import 'image-cropper.js/dist/cropper.js'
import 'image-cropper.js/dist/cropper.css'
export default {
  data () {
    return {
      token: this.$store.state.token,
      uid: this.$store.state.userId
    }
  },
  mounted () {
    var cropper = new Cropper({
      element: document.getElementById('img1'), // 显示剪裁框
      previews: [
        document.getElementById('img2') // 显示剪裁后预览框
      ],
      onCroppedRectChange: function (react) {
        console.log(react)
      }
    })
    var input = document.getElementById('imgFile')
    input.onchange = function () {
      if (typeof FileReader !== 'undefined') {
        var reader = new FileReader();
        reader.onload = function (event) {
          cropper.setImage(event.target.result);
        };
        if (input.files && input.files[0]) {
          reader.readAsDataURL(input.files[0]);
        }
      } else { // IE10-
        input.select();
        input.blur();

        var src = document.selection.createRange().text;
        cropper.setImage(src);
      }
    }
  },
  methods: {
    submit () {
      document.querySelector('form').submit()
      setTimeout(() => { // 这里不要用setTimeout，用循环判断是否为空
        var frame = document.getElementById('id_iframe');
        var text = frame.contentDocument.body.innerText;
        const resp = JSON.parse(text)
        if (resp.code !== 1) {
          this.$message.error({
            message: resp.msg,
            duration: this.$store.state.config.msgDuration
          })
        }
        console.log(22, text)
      }, 2000)
    }
  },
  computed: {
    postActionAverge () {
      return `/api/report/batchGeneratePPTPersonalReport?token=${this.token}&uid=${this.uid}&userId=${this.uid}&averageFlag=${true}`
    }
  }
}
</script>

<style lang="scss">
#img1{
  width: 300px;
  height: 200px;
  position: relative;
    overflow: hidden;
    border: 1px solid #bbb;
    margin-bottom: 5px;
  img{
    width: 100%;
    height: 100%;
  }
}
#img2{
  width: 300px;
  height: 200px;
  position: relative;
    overflow: hidden;
    border: 1px solid #bbb;
    margin-bottom: 5px;
  img{
    width: 100%;
    height: 100%;
  }
}
</style>